package com.example.asa;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/addDisaster")
public class AddDisasterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        // 验证用户角色权限
        HttpSession session = request.getSession();
        String role = (String) session.getAttribute("role");

        if (!"admin".equals(role)) {
            request.setAttribute("message", "权限不足，请先以 admin 身份登录");
            RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
            dispatcher.forward(request, response);
            return;
        }

        // 转发到添加灾情页面
        RequestDispatcher dispatcher = request.getRequestDispatcher("/addDisaster.jsp");
        dispatcher.forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");



        // 获取表单数据
        String name = request.getParameter("name");
        String location = request.getParameter("location");
        String affectedArea = request.getParameter("affected_area");
        String description = request.getParameter("description");
        String status = request.getParameter("status");
        String severity = request.getParameter("severity");
        String contact = request.getParameter("contact");

        // 验证输入数据
        if (name == null || name.isEmpty() || location == null || location.isEmpty() ||
                affectedArea == null || affectedArea.isEmpty() || description == null || description.isEmpty() ||
                status == null || status.isEmpty() || severity == null || severity.isEmpty() ||
                contact == null || contact.isEmpty()) {
            request.setAttribute("message", "所有字段都不能为空");
            RequestDispatcher dispatcher = request.getRequestDispatcher("/addDisaster.jsp");
            dispatcher.forward(request, response);
            return;
        }

        // 数据库操作 - 添加灾情信息
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = MySQLDatabaseConnector.getConnection();
            if (conn == null) {
                System.err.println("Error: 数据库连接为空");
                request.setAttribute("message", "数据库连接失败");
                RequestDispatcher dispatcher = request.getRequestDispatcher("/error.jsp");
                dispatcher.forward(request, response);
                return;
            }

            String sql = "INSERT INTO disasters (name, location, affected_area, description, status, severity, contact, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, name);
            stmt.setString(2, location);
            stmt.setString(3, affectedArea);
            stmt.setString(4, description);
            stmt.setString(5, status);
            stmt.setString(6, severity);
            stmt.setString(7, contact);

            int rowsInserted = stmt.executeUpdate();
            if (rowsInserted > 0) {
                request.setAttribute("message", "灾情信息添加成功!");
            } else {
                request.setAttribute("message", "灾情信息添加失败，请重试");
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher("emergencyPage.jsp");
            dispatcher.forward(request, response);

        } catch (SQLException e) {
            System.err.println("Error inserting disaster: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("message", "添加灾情信息时发生错误");
            RequestDispatcher dispatcher = request.getRequestDispatcher("/error.jsp");
            dispatcher.forward(request, response);
        } finally {
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
